<?php
namespace App\Service;
use App\Common\Utill\OperationLog;
use App\Models\Admin;
use App\Models\WebsitesAdmin;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;
class AdministratorService extends CommonService
{
    public function __construct()
    {
        parent::__construct();
    }

    public function getListData($request, $num)
    {
        $model = new Admin();
        $query = $model::query();
        $adminId = $this->adminId;
        $accountAuthType = self::accountAuthType();
        if($accountAuthType != 1){
            $query->where(function ($query1) use ($adminId) {
                $query1->where("id",$adminId)->orWhere('parent_id',$adminId);
            });
        }
        $username = $request->input('username','');
        if($username){
            $query->where('username','like','%'.$username.'%');
        }
        $query->where('is_del',1);
        $query->orderBy('id', 'desc');
        $result = $query->paginate($num)->toArray();
        foreach ($result['data'] as $key => $val) {
             if($val['parent_id'] == 0){
                 $result['data'][$key]['account_type']  = "主账号";
                 $result['data'][$key]['account_name']  = " - ";
             }else{
                 $result['data'][$key]['account_type'] = "子账号";
                 $result['data'][$key]['account_name']  = DB::table("pd_admins")->where("id",$val['parent_id'])->value('username');
             }
        }
        return $this->success('SUCCESS', $result['total'], $result['data']);
    }


    /**
     * 添加数据保存
     * @return void
     */
    public function create($username,$password,$parent_id)
    {
        //名称是否存在
        $existsUserName =  Admin::query()->where('username',$username)->where('is_del',1)->exists();
        if($existsUserName){
            return $this->error('该名称已存在！！！');
        }
        $adminId = $this->adminId;
        if($adminId != 1){
            $parent_id = $adminId;
        }
        $model = new Admin();
        $model->username = $username;
        $model->password = Hash::make($password);
        $model->parent_id = $parent_id ?? 0;
        $model->created_at = date("Y-m-d H:i:s");
        if (!$model->save()) {
            return $this->error('添加失败！！！');
        } else {
            OperationLog::record(1,"管理员-添加",$model->id,$model->toArray());
            return $this->success('添加成功');
        }
    }

    /**
     * 编辑
     * @param $data
     * @return void
     */
    public function update($id, $username,$password,$parent_id)
    {
        $isConfirm = Admin::query()->where('id','<>',$id)->where('username',$username)->exists();
        if($isConfirm){
            return $this->error('该名称已存在！！！');
        }
        $adminId = $this->adminId;
        $oldData = Admin::query()->where('id',$id)->first()->toArray();
        $model = Admin::findOrFail($id);
        $model->username = $username ?? '';
        if($adminId == 1){
            $model->parent_id = $parent_id ?? 0;
        }
        if($password){
            $model->password = Hash::make($password);
        }
        $model->updated_at = date("Y-m-d H:i:s");
        if (!$model->save()) {
            return $this->error('修改失败');
        }
        OperationLog::record(2,"管理员-编辑",$id,$model->toArray(),$oldData);
        return $this->success("修改成功");
    }

    /**
     * 状态修改
     * @return void
     */
    public function status($id)
    {
        $isShow = Admin::query()->where(['id'=>$id])->value('status');
        $data['status'] = $isShow == 1 ? 2 : 1;
        $data['updated_at'] = date('Y-m-d H:i:s');
        $result = Admin::query()->where('id', $id)->update($data);
        if (!$result) {
            return $this->error('设置失败');
        }
        OperationLog::record(2,"管理员-状态编辑",$id,['status'=>$data['status']],['status'=>$isShow]);
        return $this->success('设置成功');
    }

    /**
     * 单个删除
     */
    public function delOne($id)
    {
        $result = Admin::findOrFail($id);
        $result->is_del = -1;
        $result->updated_at = date("Y-m-d H:i:s");
        if (!$result->save()) {
            return $this->error('删除失败');
        }
        OperationLog::record(3,"管理员-删除",$id);
        return $this->success("删除成功");
    }

    /**
     * 批量删除
     * @return void
     */
    public function delAll($idArr)
    {
        if (!$idArr) {
            return $this->error('删除内容不能为空');
        }
        Log::info("删除id:", $idArr);
        $delData['is_del'] = -1;
        $delData['updated_at'] = date("Y-m-d H:i:s");
        $result = Admin::query()->whereIn("id", $idArr)->update($delData);
        if (!$result) {
            return $this->error('删除失败');
        }
        OperationLog::record(3,"管理员-删除",0,'','',implode(",",$idArr));
        return $this->success("删除成功");
    }

    public static function getAdminUserData()
    {
        $data = Admin::query()->where('is_del',1)->select('id','username')->orderBy('id', 'desc')->get()->toArray();
        return $data;
    }

    /**
     * 获取父级数据
     * @return mixed[]
     */
    public static function getParentData()
    {
       $parentData =  Admin::query()->where("parent_id",0)->where('is_del',1)->select('id','username')->orderBy('id', 'desc')->get()->toArray();
       return $parentData;
    }


}
